#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Attack管理器UseExample
演示如何Use统一Attack管理器进行各种Side-Channel Attack
"""

import os
import sys
import json
from pathlib import Path

# Add父DirectoryToPath
sys.path.insert(0, str(Path(__file__).parent.parent))

from attack_manager import SideChannelAttackManager, create_attack_manager, AttackConfiguration


def basic_manager_usage():
    """基础管理器UseExample"""
    
    test_data_dir = Path(__file__).parent.parent / "power_traces"
    aes_traces = test_data_dir / "aes_test_traces.npz"
    
    if not aes_traces.exists():
        print(f"[FAIL] TestDataNot存In: {aes_traces}")
        print("请先Run以下CommandGenerateTestData:")
        print("cd /home/ga4ss/workspace/j0ker/xchip")
        print("python3 tools/power_trace_generator.py -a aes -n 50 -o side_channel_attacks/power_traces/aes_test_traces.npz --noise")
        return False
    
    print("[Target] 基础Attack管理器UseExample")
    print("-" * 50)
    
    try:
        # Method1: 手动Create管理器
        print("[Note] Method1: 手动Create管理器")
        manager = SideChannelAttackManager(log_level="WARNING")  # 减少日志Output
        
        # LoadData
        if manager.load_data(str(aes_traces)):
            print("[OK] DataLoadSuccess")
            print(f"  - Algorithm: {manager.algorithm}")
            print(f"  - Trace数量: {len(manager.traces)}")
            print(f"  - Trace长度: {manager.traces.shape[1]}")
        else:
            print("[FAIL] DataLoadFailed")
            return False
        
        print()
        
        # Method2: Use便捷Function
        print("[Note] Method2: Use便捷Function")
        manager2 = create_attack_manager(str(aes_traces), log_level="WARNING")
        print("[OK] 便捷FunctionCreate管理器Success")
        
        return manager
        
    except Exception as e:
        print(f"[FAIL] 管理器CreateFailed: {e}")
        return False


def run_individual_attacks(manager):
    """Run单独AttackExample"""
    
    print("\n[Target] 单独AttackExample")
    print("-" * 50)
    
    # 1. 基础CPAAttack
    print("1. 基础CPAAttack")
    try:
        result = manager.run_basic_attack('cpa', target_byte=0)
        print(f"   Result: Success={result.success}, 置信度={result.confidence:.4f}, 时间={result.execution_time:.2f}s")
    except Exception as e:
        print(f"   Failed: {e}")
    
    # 2. 基础DPAAttack
    print("2. 基础DPAAttack")
    try:
        result = manager.run_basic_attack('dpa', target_byte=0)
        print(f"   Result: Success={result.success}, 置信度={result.confidence:.4f}, 时间={result.execution_time:.2f}s")
    except Exception as e:
        print(f"   Failed: {e}")
    
    # 3. Algorithm特定CPAAttack
    print("3. Algorithm特定CPAAttack")
    try:
        result = manager.run_algorithm_specific_attack('cpa', target_operation="sbox_output")
        print(f"   Result: Success={result.success}, 置信度={result.confidence:.4f}, 时间={result.execution_time:.2f}s")
        print(f"   Algorithm: {result.algorithm}, 目标操作: {result.target_operation}")
    except Exception as e:
        print(f"   Failed: {e}")
    
    # 4. Algorithm特定DPAAttack
    print("4. Algorithm特定DPAAttack")
    try:
        result = manager.run_algorithm_specific_attack('dpa', target_operation="sbox_output")
        print(f"   Result: Success={result.success}, 置信度={result.confidence:.4f}, 时间={result.execution_time:.2f}s")
    except Exception as e:
        print(f"   Failed: {e}")


def run_comprehensive_attack(manager):
    """Run综合AttackExample"""
    
    print("\n[Target] 综合AttackExample")
    print("-" * 50)
    
    try:
        # RunAllAttackClass型
        results = manager.run_comprehensive_attack(
            target_byte=0,
            attack_types=['cpa', 'dpa', 'spa', 'template']
        )
        
        print("综合AttackResult:")
        print(f"  - Algorithm: {results['algorithm']}")
        print(f"  - 目标字节: {results['target_byte']}")
        
        # 基础AttackResult
        print("\n基础AttackResult:")
        for attack_type, result in results['basic_attacks'].items():
            if 'error' in result:
                print(f"  {attack_type.upper()}: Error - {result['error']}")
            else:
                success = "[OK]" if result['success'] else "[FAIL]"
                print(f"  {attack_type.upper()}: {success} 置信度={result['confidence']:.4f}")
        
        # Algorithm特定AttackResult
        print("\nAlgorithm特定AttackResult:")
        for attack_type, result in results['algorithm_specific_attacks'].items():
            if 'error' in result:
                print(f"  {attack_type.upper()}: Error - {result['error']}")
            else:
                success = "[OK]" if result['success'] else "[FAIL]"
                print(f"  {attack_type.upper()}: {success} 置信度={result['confidence']:.4f}")
        
        # 摘要Information
        summary = results['summary']
        print(f"\n[Stats] Attack摘要:")
        print(f"  - 基础AttackSuccess: {summary['basic_attacks_success']}/{summary['basic_attacks_total']}")
        print(f"  - Algorithm特定AttackSuccess: {summary['algorithm_specific_success']}/{summary['algorithm_specific_total']}")
        print(f"  - 总体Success率: {summary['overall_success_rate']:.1%}")
        
        # SaveResult
        output_dir = Path(__file__).parent.parent / "attack_results"
        filepath = manager.save_results(results, str(output_dir), "comprehensive_attack_results.json")
        print(f"\n[Save] Result已SaveTo: {filepath}")
        
        return results
        
    except Exception as e:
        print(f"[FAIL] 综合AttackFailed: {e}")
        return None


def demonstrate_manager_features(manager):
    """演示管理器功能"""
    
    print("\n[Tool] 管理器功能演示")
    print("-" * 50)
    
    # 1. 获取可用Algorithm
    algorithms = manager.get_available_algorithms()
    print(f"可用Algorithm: {algorithms}")
    
    # 2. 获取可用Attack
    attacks = manager.get_available_attacks()
    print(f"可用Attack: {attacks}")
    
    # 3. 获取AlgorithmInformation
    info = manager.get_algorithm_info()
    print(f"\nCurrentAlgorithmInformation:")
    if 'error' not in info:
        print(f"  - Algorithm: {info['algorithm']}")
        print(f"  - Parameters: {info['parameters']}")
        print(f"  - 目标操作: {info['target_operations']}")
        print(f"  - 泄漏模型: {info['leakage_models']}")
    else:
        print(f"  Error: {info['error']}")
    
    # 4. 获取其他AlgorithmInformation
    print(f"\n其他AlgorithmInformation:")
    for algorithm in ['sm4', 'rsa']:
        info = manager.get_algorithm_info(algorithm)
        if 'error' not in info:
            print(f"  {algorithm.upper()}: {len(info['target_operations'])} 个目标操作, {len(info['leakage_models'])} 个泄漏模型")
        else:
            print(f"  {algorithm.upper()}: {info['error']}")


def test_different_algorithms():
    """TestNot同Algorithm"""
    
    print("\n[Refresh] Not同AlgorithmTest")
    print("-" * 50)
    
    test_data_dir = Path(__file__).parent.parent / "power_traces"
    test_files = {
        'aes': test_data_dir / "aes_test_traces.npz",
        'sm4': test_data_dir / "sm4_test_traces.npz"
    }
    
    for algorithm, trace_file in test_files.items():
        if not trace_file.exists():
            print(f"[WARNING] {algorithm.upper()}TestDataNot存In: {trace_file}")
            continue
        
        print(f"\nTest {algorithm.upper()} Algorithm:")
        try:
            manager = create_attack_manager(str(trace_file), algorithm=algorithm, log_level="ERROR")
            
            # Run快速CPAAttack
            result = manager.run_basic_attack('cpa', target_byte=0)
            print(f"  基础CPA: Success={result.success}, 置信度={result.confidence:.4f}")
            
            # RunAlgorithm特定Attack
            result = manager.run_algorithm_specific_attack('cpa', target_operation="sbox_output")
            print(f"  特定CPA: Success={result.success}, 置信度={result.confidence:.4f}")
            
        except Exception as e:
            print(f"  [FAIL] TestFailed: {e}")


def configuration_example():
    """ConfigurationExample"""
    
    print("\n[Config] AttackConfigurationExample")
    print("-" * 50)
    
    # CreateNot同Configuration
    configs = [
        AttackConfiguration(),  # DefaultConfiguration
        AttackConfiguration(
            algorithm="sm4",
            attack_type="dpa",
            target_byte=1,
            threshold=0.2,
            verbose=True
        ),
        AttackConfiguration(
            algorithm="aes",
            attack_type="template",
            target_operation="first_round",
            save_results=False
        )
    ]
    
    print("ConfigurationExample:")
    for i, config in enumerate(configs, 1):
        print(f"  Configuration {i}:")
        print(f"    - Algorithm: {config.algorithm}")
        print(f"    - AttackClass型: {config.attack_type}")
        print(f"    - 目标字节: {config.target_byte}")
        print(f"    - 目标操作: {config.target_operation}")
        print(f"    - 阈值: {config.threshold}")
        print(f"    - DetailedOutput: {config.verbose}")
        print(f"    - SaveResult: {config.save_results}")
        print()


if __name__ == "__main__":
    try:
        print("=" * 60)
        print("Attack管理器UseExample")
        print("=" * 60)
        
        # 基础Use
        manager = basic_manager_usage()
        if not manager:
            sys.exit(1)
        
        # 单独Attack
        run_individual_attacks(manager)
        
        # 综合Attack
        comprehensive_results = run_comprehensive_attack(manager)
        
        # 功能演示
        demonstrate_manager_features(manager)
        
        # Not同AlgorithmTest
        test_different_algorithms()
        
        # ConfigurationExample
        configuration_example()
        
        print("\n=" * 60)
        print("Attack管理器ExampleCompleted")
        print("=" * 60)
        
        # Output最终总结
        if comprehensive_results:
            summary = comprehensive_results['summary']
            total_success = summary['basic_attacks_success'] + summary['algorithm_specific_success']
            total_attacks = summary['basic_attacks_total'] + summary['algorithm_specific_total']
            
            print(f"\n[Success] 总体AttackResult: {total_success}/{total_attacks} Success")
            print(f"[Stats] Success率: {summary['overall_success_rate']:.1%}")
        
    except KeyboardInterrupt:
        print("\n[WARNING] 用户Interrupt操作")
    except Exception as e:
        print(f"\n[FAIL] ExampleRunFailed: {e}")
        sys.exit(1)
